package com.jumi.microservice.wdt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jumi.microservice.common.exception.BaseException;
import com.jumi.microservice.dto.logistics.NoticeMaterialRequest;
import com.jumi.microservice.dto.wdt.WdtLogisticsRequest;
import com.jumi.microservice.dto.wdt.WdtLogisticsResponse;
import com.jumi.microservice.dto.wdt.WdtOrderRequest;
import com.jumi.microservice.service.logistics.admin.SendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dirk
 * @Date 2020-08-20 14:50
 */
@Component
@RefreshScope
public class WdtOrderClient {

    private static final Logger log = LoggerFactory.getLogger(WdtOrderClient.class);

    private static final String LOGISTICS_NO_PREFIX = "JM";

    @Resource
    private WdtClient wdtClient;

    @Value("${wdt.tradePush:/trade_push.php}")
    private String pushOrderUrl;

    @Value("${wdt.tradePush:/logistics_sync_query.php}")
    private String logisticsSyncQueryUrl;

    @Value("${wdt.tradePush:/logistics_sync_ack.php}")
    private String logisticsSyncAckUrl;

    @Value("${wdt.shopNo}")
    private String shopNo;

    @Resource
    private WdtRequestConvert wdtRequestConvert;

    @Resource
    private SendService sendService;

    public void pushOrder(List<WdtOrderRequest> wdtOrderRequestList) {
        List<Map<String, Object>> tradeList = wdtRequestConvert.orderListConvert(wdtOrderRequestList);
        Map<String, Object> params = new HashMap<>();
        params.put("shop_no", shopNo);
        params.put("trade_list", JSON.toJSONString(tradeList, SerializerFeature.WriteDateUseDateFormat));
        String response = null;
        try {
            log.info("wdt push order : params => [{}]", JSON.toJSONString(params));
            response = wdtClient.execute(pushOrderUrl, params);
            log.info("wdt push order : response => [{}]", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") != 0) {
            throw new BaseException(jsonObject.getInteger("code"), jsonObject.getString("message"));
        }
    }

    public void logisticsSync() {
        Map<String, Object> params = new HashMap<>();
        params.put("limit", 100);
        String response = null;
        try {
            log.info("wdt logistics sync query : params => [{}]", JSON.toJSONString(params));
            response = wdtClient.execute(logisticsSyncQueryUrl, params);
            log.info("wdt logistics sync query : response => [{}]", response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        if (jsonObject.getInteger("code") != 0) {
            throw new BaseException(jsonObject.getInteger("code"), jsonObject.getString("message"));
        }
        JSONArray jsonArray = jsonObject.getJSONArray("trades");
        List<WdtLogisticsResponse> logisticsResponseList = jsonArray.toJavaList(WdtLogisticsResponse.class);
        if (logisticsResponseList.isEmpty()) {
            return;
        }
        List<WdtLogisticsRequest> wdtLogisticsRequestList = new ArrayList<>();
        List<NoticeMaterialRequest> noticeMaterialRequestList = new ArrayList<>();
        logisticsResponseList.forEach(wdtLogisticsResponse -> {
            if (wdtLogisticsResponse.getTid().startsWith(LOGISTICS_NO_PREFIX)) {
                // 包裹发货
                NoticeMaterialRequest noticeMaterialRequest = new NoticeMaterialRequest();
                noticeMaterialRequest.setLogisticsNo(wdtLogisticsResponse.getTid());
                noticeMaterialRequest.setRealLogisticsNo(wdtLogisticsResponse.getLogistics_no());
//                wdtLogisticsResponse.getLogistics_type()
//                wdtLogisticsResponse.getLogistics_name()
                noticeMaterialRequest.setExpressCompany(wdtLogisticsResponse.getLogistics_name_erp());
                noticeMaterialRequestList.add(noticeMaterialRequest);
                // 物流同步回写
                WdtLogisticsRequest wdtLogisticsRequest = new WdtLogisticsRequest();
                wdtLogisticsRequest.setRecId(wdtLogisticsResponse.getRec_id());
                wdtLogisticsRequest.setStatus(new Byte("1"));
                wdtLogisticsRequestList.add(wdtLogisticsRequest);
            }
        });
        if (noticeMaterialRequestList.isEmpty() || wdtLogisticsRequestList.isEmpty()) {
            return;
        }
//        sendService.noticeMaterialByLogisticsNo(noticeMaterialRequestList);

        Map<String, Object> ackParams = new HashMap<>();
        ackParams.put("logistics_list", JSON.toJSONString(wdtRequestConvert.logisticsListConvert(wdtLogisticsRequestList)));
        String ackResponse = null;
        try {
            log.info("wdt logistics sync ack : params => [{}]", JSON.toJSONString(ackParams));
            ackResponse = wdtClient.execute(logisticsSyncAckUrl, ackParams);
            log.info("wdt logistics sync ack : response => [{}]", ackResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject ackJsonObject = JSONObject.parseObject(ackResponse);
        if (ackJsonObject.getInteger("code") != 0) {
            throw new BaseException(ackJsonObject.getInteger("code"), ackJsonObject.getString("message"));
        }
    }
}
